#-*- coding:utf-8 -*-
import re
import requests
import os
import shutil


def dowmloadPic(html,keyword,j):
    if os.path.exists(keyword):
        shutil.rmtree(keyword)
        os.makedirs(keyword)
    else:
        os.makedirs(keyword)
    pic_url = re.findall('"objURL":"(.*?)",',html,re.S)
    i = 0
    print ('找到关键词:'+keyword+'的图片，现在开始下载图片...')
    count = 0
    j = j
    while(count < j):
        for each in pic_url:
            print ('正在下载第'+str(i+1)+'张图片')
            try:
                pic= requests.get(each, timeout=10)
            except requests.exceptions.ConnectionError:
                print ('【错误】当前图片无法下载')
                continue
            string = str(keyword)+'\\'+keyword+'_'+str(i) + '.jpg'
            #resolve the problem of encode, make sure that chinese name could be store
            fp = open(string,'wb')
            fp.write(pic.content)
            fp.close()
            i += 1
        count += 1
    print('下载完成!!!')



if __name__ == '__main__':
    word = input("Input key word: ")
    
    t = 0
    url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word='+word+'&pn='+str(t)+'&gsm=3c&ct=&ic=0&lm=-1&width=0&height=0'
    result = requests.get(url)
    j = int(input('请输入需要爬取的图片页数(一页60张):'))
    dowmloadPic(result.text,word,j)
